import React, { useState, useEffect, useCallback } from "react";
import {
  Modal,
  Steps,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  Card,
  List,
  Tag,
  Space,
  message,
  Spin,
  Empty,
  Tooltip,
  Progress,
  Row,
  Col,
  Divider,
  Alert,
  Checkbox,
  Table,
  Popconfirm,
} from "antd";
import {
  BulbOutlined,
  PlusOutlined,
  DeleteOutlined,
  EyeOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  RobotOutlined,
  DragOutlined,
  OrderedListOutlined,
  ThunderboltOutlined,
} from "@ant-design/icons";
// 暂时移除 react-beautiful-dnd，使用简单的拖拽功能
// import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
import type { ColumnsType } from "antd/es/table";
import {
  questionAPI,
  examComposerAPI,
  type Question,
  type AIQuestionRequest,
  type ExamComposer,
} from "../../../../services/examService";

const { Option } = Select;
const { TextArea } = Input;

interface SmartComposerProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: (examData: any) => void;
  courseId?: string;
  classId?: string;
}

interface SelectedQuestion extends Question {
  customScore?: number;
  order: number;
  isRequired: boolean;
}

interface CompositionStats {
  totalQuestions: number;
  totalScore: number;
  estimatedDuration: number;
  difficultyDistribution: {
    easy: number;
    medium: number;
    hard: number;
  };
  typeDistribution: {
    choice: number;
    programming: number;
    analysis: number;
  };
}

const SmartComposer: React.FC<SmartComposerProps> = ({
  visible,
  onCancel,
  onSuccess,
  courseId,
  classId,
}) => {
  const [currentStep, setCurrentStep] = useState(0);
  const [form] = Form.useForm();

  // 状态管理
  const [loading, setLoading] = useState(false);
  const [aiGenerating, setAiGenerating] = useState(false);
  const [availableQuestions, setAvailableQuestions] = useState<Question[]>([]);
  const [selectedQuestions, setSelectedQuestions] = useState<
    SelectedQuestion[]
  >([]);
  const [compositionStats, setCompositionStats] = useState<CompositionStats>({
    totalQuestions: 0,
    totalScore: 0,
    estimatedDuration: 0,
    difficultyDistribution: { easy: 0, medium: 0, hard: 0 },
    typeDistribution: { choice: 0, programming: 0, analysis: 0 },
  });
  const [aiSuggestions, setAiSuggestions] = useState<string[]>([]);
  const [knowledgePoints, setKnowledgePoints] = useState<string[]>([]);

  // 步骤配置
  const steps = [
    {
      title: "基本信息",
      description: "设置考试基本信息",
    },
    {
      title: "AI生成题目",
      description: "使用AI生成题目库",
    },
    {
      title: "智能选题",
      description: "选择和排序题目",
    },
    {
      title: "预览确认",
      description: "预览和确认试卷",
    },
  ];

  // 重置组件状态
  const resetState = useCallback(() => {
    setCurrentStep(0);
    setAvailableQuestions([]);
    setSelectedQuestions([]);
    setAiSuggestions([]);
    setKnowledgePoints([]);
    form.resetFields();
  }, [form]);

  // 组件卸载时重置状态
  useEffect(() => {
    if (!visible) {
      resetState();
    }
  }, [visible, resetState]);

  // 计算组卷统计
  useEffect(() => {
    const stats: CompositionStats = {
      totalQuestions: selectedQuestions.length,
      totalScore: selectedQuestions.reduce(
        (sum, q) => sum + (q.customScore || q.score),
        0
      ),
      estimatedDuration: selectedQuestions.reduce((sum, q) => {
        // 根据题目类型估算时间
        const baseDuration =
          q.type === "choice" ? 2 : q.type === "programming" ? 15 : 8;
        return sum + baseDuration;
      }, 0),
      difficultyDistribution: {
        easy: selectedQuestions.filter((q) => q.difficulty === "easy").length,
        medium: selectedQuestions.filter((q) => q.difficulty === "medium")
          .length,
        hard: selectedQuestions.filter((q) => q.difficulty === "hard").length,
      },
      typeDistribution: {
        choice: selectedQuestions.filter((q) => q.type === "choice").length,
        programming: selectedQuestions.filter((q) => q.type === "programming")
          .length,
        analysis: selectedQuestions.filter((q) => q.type === "analysis").length,
      },
    };
    setCompositionStats(stats);
  }, [selectedQuestions]);

  // AI生成题目
  const handleAIGenerate = async (values: any) => {
    setAiGenerating(true);
    try {
      // 模拟AI生成过程
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 生成模拟题目数据
      const mockQuestions: Question[] = [];
      const { knowledgePoints, subject, targetGrade, totalQuestions } = values;
      
      // 生成选择题
      const choiceCount = Math.floor(totalQuestions * 0.6);
      for (let i = 0; i < choiceCount; i++) {
        mockQuestions.push({
          id: `ai_choice_${Date.now()}_${i}`,
          type: "choice",
          title: `AI生成的${subject}选择题 ${i + 1}`,
          content: `关于${subject}的选择题内容 ${i + 1}，涉及${knowledgePoints?.[0] || '基础知识'}。`,
          difficulty: i % 3 === 0 ? 1 : i % 3 === 1 ? 2 : 3,
          score: 5,
          answer: String.fromCharCode(65 + (i % 4)),
          knowledgePoint: knowledgePoints?.[0] || `${subject}基础知识`,
          options: [
            `选项A：${subject}相关选项A`,
            `选项B：${subject}相关选项B`, 
            `选项C：${subject}相关选项C`,
            `选项D：${subject}相关选项D`
          ],
          analysis: `这是一道关于${subject}的${i % 3 === 0 ? '简单' : i % 3 === 1 ? '中等' : '困难'}难度选择题。`
        });
      }
      
      // 生成编程题
      const programmingCount = Math.floor(totalQuestions * 0.25);
      for (let i = 0; i < programmingCount; i++) {
        mockQuestions.push({
          id: `ai_programming_${Date.now()}_${i}`,
          type: "programming",
          title: `AI生成的${subject}编程题 ${i + 1}`,
          content: `请编写一个函数来解决${subject}相关的编程问题 ${i + 1}。`,
          difficulty: i % 2 === 0 ? 2 : 3,
          score: 20,
          answer: `function solution${i + 1}() {\n  // 解决方案\n  return result;\n}`,
          knowledgePoint: knowledgePoints?.[0] || `${subject}编程`,
          analysis: `这是一道关于${subject}的编程题，考察编程实践能力。`
        });
      }
      
      // 生成分析题
      const analysisCount = totalQuestions - choiceCount - programmingCount;
      for (let i = 0; i < analysisCount; i++) {
        mockQuestions.push({
          id: `ai_analysis_${Date.now()}_${i}`,
          type: "analysis",
          title: `AI生成的${subject}分析题 ${i + 1}`,
          content: `请分析${subject}中的某个概念或现象 ${i + 1}，并说明其原理和应用。`,
          difficulty: 3,
          score: 15,
          answer: `分析要点：\n1. 概念解释\n2. 原理说明\n3. 应用场景\n4. 优缺点分析`,
          knowledgePoint: knowledgePoints?.[0] || `${subject}理论`,
          analysis: `这是一道关于${subject}的分析题，考察理论理解和分析能力。`
        });
      }
      
      setAvailableQuestions(mockQuestions);
      setKnowledgePoints(knowledgePoints);
      message.success(`AI成功生成 ${mockQuestions.length} 道题目！`);
      
      // 生成AI建议
      const mockSuggestions = [
        `建议选择${Math.floor(choiceCount * 0.7)}道选择题，覆盖基础知识`,
        `建议选择${Math.floor(programmingCount * 0.8)}道编程题，注重实践能力`,
        `建议选择${Math.floor(analysisCount * 0.6)}道分析题，考察理论深度`,
        `总体难度建议控制在中等水平，适合${targetGrade}学生`
      ];
      setAiSuggestions(mockSuggestions);
      
      setCurrentStep(2);
    } catch (error) {
      console.error("AI生成题目失败:", error);
      message.error("AI生成失败，请检查网络连接或稍后重试");
    } finally {
      setAiGenerating(false);
    }
  };

  // 智能选题建议
  const handleSmartSelection = async () => {
    try {
      const formValues = await form.getFieldsValue();
      
      // 模拟智能选题
      const smartSelected = availableQuestions
        .filter(q => !selectedQuestions.find(sq => sq.id === q.id))
        .slice(0, Math.min(5, availableQuestions.length - selectedQuestions.length))
        .map((q, index) => ({
          ...q,
          order: selectedQuestions.length + index + 1,
          isRequired: true,
          customScore: q.score,
        }));

      setSelectedQuestions((prev) => [...prev, ...smartSelected]);
      message.success(`智能选择了 ${smartSelected.length} 道题目`);
    } catch (error) {
      console.error("智能选题失败:", error);
      message.error("智能选题失败");
    }
  };

  // 添加题目到试卷
  const addQuestion = (question: Question) => {
    const newQuestion: SelectedQuestion = {
      ...question,
      order: selectedQuestions.length + 1,
      isRequired: true,
      customScore: question.score,
    };
    setSelectedQuestions((prev) => [...prev, newQuestion]);
    message.success("题目已添加到试卷");
  };

  // 移除题目
  const removeQuestion = (index: number) => {
    setSelectedQuestions((prev) => {
      const newList = prev.filter((_, i) => i !== index);
      return newList.map((q, i) => ({ ...q, order: i + 1 }));
    });
  };

  // 上移题目
  const moveQuestionUp = (index: number) => {
    if (index === 0) return;

    setSelectedQuestions((prev) => {
      const newList = [...prev];
      [newList[index], newList[index - 1]] = [
        newList[index - 1],
        newList[index],
      ];
      return newList.map((q, i) => ({ ...q, order: i + 1 }));
    });
  };

  // 下移题目
  const moveQuestionDown = (index: number) => {
    if (index === selectedQuestions.length - 1) return;

    setSelectedQuestions((prev) => {
      const newList = [...prev];
      [newList[index], newList[index + 1]] = [
        newList[index + 1],
        newList[index],
      ];
      return newList.map((q, i) => ({ ...q, order: i + 1 }));
    });
  };

  // 更新题目分值
  const updateQuestionScore = (index: number, score: number) => {
    setSelectedQuestions((prev) =>
      prev.map((q, i) => (i === index ? { ...q, customScore: score } : q))
    );
  };

  // 完成组卷
  const handleFinish = async () => {
    try {
      setLoading(true);
      const formValues = await form.getFieldsValue();

      const examData: ExamComposer = {
        title: formValues.examName || "智能组卷试卷",
        description: `${formValues.examType || "考试"} - ${formValues.subject || ""}`,
        questions: selectedQuestions,
        totalScore: compositionStats.totalScore,
        duration: compositionStats.estimatedDuration,
        difficulty: "medium", // 默认中等难度
        knowledgePoints: formValues.knowledgePoints || [],
        examName: formValues.examName,
        examType: formValues.examType,
        targetClass: classId || formValues.targetClass,
        targetCourse: courseId || formValues.targetCourse,
        questionSelection: selectedQuestions.map((q) => ({
          questionId: q.id,
          score: q.customScore || q.score,
          order: q.order,
          isRequired: q.isRequired,
        })),
        aiSuggestions,
        estimatedDuration: compositionStats.estimatedDuration,
      };

      // 模拟保存组卷方案
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success("智能组卷完成！");
      onSuccess(examData);
      onCancel();
    } catch (error) {
      console.error("保存组卷方案失败:", error);
      message.error("保存失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  // 可用题目表格列定义
  const questionColumns: ColumnsType<Question> = [
    {
      title: "类型",
      dataIndex: "type",
      width: 80,
      render: (type: Question["type"]) => {
        const typeMap: Record<string, { color: string; text: string }> = {
          choice: { color: "blue", text: "选择" },
          programming: { color: "purple", text: "编程" },
          analysis: { color: "cyan", text: "分析" },
          single: { color: "blue", text: "单选" },
          multiple: { color: "blue", text: "多选" },
          judge: { color: "green", text: "判断" },
          fill: { color: "orange", text: "填空" },
          essay: { color: "red", text: "论述" },
        };
        const mappedType = typeMap[type] || {
          color: "default",
          text: String(type),
        };
        return <Tag color={mappedType.color}>{mappedType.text}</Tag>;
      },
    },
    {
      title: "难度",
      dataIndex: "difficulty",
      width: 80,
      render: (difficulty: Question["difficulty"]) => {
        const difficultyMap: Record<string, { color: string; text: string }> = {
          easy: { color: "green", text: "简单" },
          medium: { color: "orange", text: "中等" },
          hard: { color: "red", text: "困难" },
          "1": { color: "green", text: "简单" },
          "2": { color: "orange", text: "中等" },
          "3": { color: "red", text: "困难" },
        };
        const mappedDifficulty = difficultyMap[String(difficulty)] || {
          color: "default",
          text: String(difficulty),
        };
        return (
          <Tag color={mappedDifficulty.color}>{mappedDifficulty.text}</Tag>
        );
      },
    },
    {
      title: "题目内容",
      dataIndex: "content",
      ellipsis: true,
      render: (content: string) => (
        <Tooltip title={content}>
          <span>{content.substring(0, 50)}...</span>
        </Tooltip>
      ),
    },
    {
      title: "分值",
      dataIndex: "score",
      width: 60,
    },
    {
      title: "操作",
      width: 100,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="预览">
            <Button type="link" size="small" icon={<EyeOutlined />} />
          </Tooltip>
          <Tooltip title="添加到试卷">
            <Button
              type="link"
              size="small"
              icon={<PlusOutlined />}
              onClick={() => addQuestion(record)}
              disabled={selectedQuestions.some((q) => q.id === record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 渲染步骤内容
  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Form
            form={form}
            layout="vertical"
            onFinish={() => setCurrentStep(1)}
          >
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="examName"
                  label="考试名称"
                  rules={[{ required: true, message: "请输入考试名称" }]}
                >
                  <Input placeholder="如：期中考试、第一次作业" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="examType"
                  label="类型"
                  rules={[{ required: true, message: "请选择类型" }]}
                >
                  <Select placeholder="请选择">
                    <Option value="exam">考试</Option>
                    <Option value="homework">作业</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="subject"
                  label="科目"
                  rules={[{ required: true, message: "请输入科目" }]}
                >
                  <Input placeholder="如：操作系统、数据结构" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="targetGrade"
                  label="目标年级"
                  rules={[{ required: true, message: "请选择年级" }]}
                >
                  <Select placeholder="请选择">
                    <Option value="大一">大一</Option>
                    <Option value="大二">大二</Option>
                    <Option value="大三">大三</Option>
                    <Option value="大四">大四</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={24}>
              <Col span={8}>
                <Form.Item
                  name="totalQuestions"
                  label="题目总数"
                  rules={[{ required: true, message: "请输入题目数量" }]}
                >
                  <InputNumber min={5} max={50} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="targetScore"
                  label="总分"
                  rules={[{ required: true, message: "请输入总分" }]}
                >
                  <InputNumber min={50} max={200} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="duration"
                  label="时长(分钟)"
                  rules={[{ required: true, message: "请输入考试时长" }]}
                >
                  <InputNumber min={30} max={300} style={{ width: "100%" }} />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="knowledgePoints"
              label="知识点"
              rules={[{ required: true, message: "请选择知识点" }]}
            >
              <Select
                mode="tags"
                placeholder="请输入或选择知识点"
                style={{ width: "100%" }}
              >
                <Option value="进程管理">进程管理</Option>
                <Option value="内存管理">内存管理</Option>
                <Option value="文件系统">文件系统</Option>
                <Option value="设备管理">设备管理</Option>
              </Select>
            </Form.Item>

            <Form.Item name="requirements" label="特殊要求">
              <TextArea rows={3} placeholder="请描述对题目的特殊要求..." />
            </Form.Item>
          </Form>
        );

      case 1:
        return (
          <div>
            <Alert
              message="AI智能生成题目"
              description="基于您的配置，AI将生成多样化的题目供您选择。这可能需要几分钟时间。"
              type="info"
              style={{ marginBottom: 24 }}
            />

            {aiGenerating ? (
              <div style={{ textAlign: "center", padding: "60px 0" }}>
                <Spin size="large" />
                <div style={{ marginTop: 16 }}>
                  <RobotOutlined style={{ fontSize: 24, color: "#1890ff" }} />
                  <div>AI正在分析您的需求并生成题目...</div>
                  <Progress
                    percent={65}
                    style={{ marginTop: 16, maxWidth: 400 }}
                  />
                </div>
              </div>
            ) : (
              <div style={{ textAlign: "center", padding: "60px 0" }}>
                <Button
                  type="primary"
                  size="large"
                  icon={<ThunderboltOutlined />}
                  onClick={() => form.submit()}
                  loading={aiGenerating}
                >
                  开始AI生成题目
                </Button>
              </div>
            )}

            {aiSuggestions.length > 0 && (
              <Card title="AI建议" style={{ marginTop: 24 }}>
                <List
                  dataSource={aiSuggestions}
                  renderItem={(item, index) => (
                    <List.Item>
                      <BulbOutlined
                        style={{ color: "#faad14", marginRight: 8 }}
                      />
                      {item}
                    </List.Item>
                  )}
                />
              </Card>
            )}
          </div>
        );

      case 2:
        return (
          <Row gutter={24}>
            <Col span={14}>
              <Card
                title="可用题目"
                extra={
                  <Button
                    type="primary"
                    icon={<BulbOutlined />}
                    onClick={handleSmartSelection}
                  >
                    智能选题
                  </Button>
                }
              >
                {availableQuestions.length > 0 ? (
                  <Table
                    columns={questionColumns}
                    dataSource={availableQuestions}
                    rowKey="id"
                    size="small"
                    pagination={{ pageSize: 10 }}
                  />
                ) : (
                  <Empty description="暂无可用题目" />
                )}
              </Card>
            </Col>

            <Col span={10}>
              <Card
                title="已选题目"
                extra={
                  <Space>
                    <Tag color="blue">{selectedQuestions.length} 题</Tag>
                    <Tag color="green">{compositionStats.totalScore} 分</Tag>
                  </Space>
                }
              >
                <div style={{ minHeight: 200 }}>
                  {selectedQuestions.length > 0 ? (
                    selectedQuestions.map((question, index) => (
                      <Card
                        key={question.id}
                        size="small"
                        style={{ marginBottom: 8 }}
                      >
                        <div style={{ display: "flex", alignItems: "center" }}>
                          <div style={{ flex: 1 }}>
                            <div>
                              <Tag color="blue">{question.order}</Tag>
                              <span>
                                {question.content.substring(0, 30)}...
                              </span>
                            </div>
                            <div style={{ marginTop: 4 }}>
                              <InputNumber
                                size="small"
                                min={1}
                                max={50}
                                value={question.customScore}
                                onChange={(value) =>
                                  updateQuestionScore(
                                    index,
                                    value || question.score
                                  )
                                }
                                style={{ width: 80 }}
                              />
                              <span style={{ marginLeft: 8 }}>分</span>
                            </div>
                          </div>

                          <Space>
                            <Tooltip title="上移">
                              <Button
                                type="link"
                                size="small"
                                icon={<span>↑</span>}
                                onClick={() => moveQuestionUp(index)}
                                disabled={index === 0}
                              />
                            </Tooltip>
                            <Tooltip title="下移">
                              <Button
                                type="link"
                                size="small"
                                icon={<span>↓</span>}
                                onClick={() => moveQuestionDown(index)}
                                disabled={
                                  index === selectedQuestions.length - 1
                                }
                              />
                            </Tooltip>
                            <Popconfirm
                              title="确定移除此题目吗？"
                              onConfirm={() => removeQuestion(index)}
                            >
                              <Button
                                type="link"
                                size="small"
                                danger
                                icon={<DeleteOutlined />}
                              />
                            </Popconfirm>
                          </Space>
                        </div>
                      </Card>
                    ))
                  ) : (
                    <Empty
                      description="请从左侧选择题目"
                      image={Empty.PRESENTED_IMAGE_SIMPLE}
                    />
                  )}
                </div>
              </Card>

              {/* 统计信息 */}
              <Card title="试卷统计" style={{ marginTop: 16 }}>
                <Row gutter={16}>
                  <Col span={12}>
                    <div>
                      题目数量:{" "}
                      <strong>{compositionStats.totalQuestions}</strong>
                    </div>
                    <div>
                      总分: <strong>{compositionStats.totalScore}</strong>
                    </div>
                    <div>
                      预计时长:{" "}
                      <strong>{compositionStats.estimatedDuration}分钟</strong>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div>
                      简单: {compositionStats.difficultyDistribution.easy}
                    </div>
                    <div>
                      中等: {compositionStats.difficultyDistribution.medium}
                    </div>
                    <div>
                      困难: {compositionStats.difficultyDistribution.hard}
                    </div>
                  </Col>
                </Row>
              </Card>
            </Col>
          </Row>
        );

      case 3:
        return (
          <div>
            <Card title="试卷预览" style={{ marginBottom: 24 }}>
              <Row gutter={24}>
                <Col span={12}>
                  <div>
                    <strong>考试名称:</strong> {form.getFieldValue("examName")}
                  </div>
                  <div>
                    <strong>类型:</strong>{" "}
                    {form.getFieldValue("examType") === "exam"
                      ? "考试"
                      : "作业"}
                  </div>
                  <div>
                    <strong>科目:</strong> {form.getFieldValue("subject")}
                  </div>
                  <div>
                    <strong>年级:</strong> {form.getFieldValue("targetGrade")}
                  </div>
                </Col>
                <Col span={12}>
                  <div>
                    <strong>题目数量:</strong> {compositionStats.totalQuestions}
                  </div>
                  <div>
                    <strong>总分:</strong> {compositionStats.totalScore}
                  </div>
                  <div>
                    <strong>预计时长:</strong>{" "}
                    {compositionStats.estimatedDuration}分钟
                  </div>
                </Col>
              </Row>
            </Card>

            <Card title="题目列表">
              <List
                dataSource={selectedQuestions.sort((a, b) => a.order - b.order)}
                renderItem={(question, index) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Tag color="blue">{question.order}</Tag>}
                      title={
                        <Space>
                          <span>{question.content}</span>
                          <Tag color="green">{question.customScore}分</Tag>
                        </Space>
                      }
                      description={
                        <Space>
                          <Tag>
                            {question.type === "choice"
                              ? "选择题"
                              : question.type === "programming"
                                ? "编程题"
                                : "分析题"}
                          </Tag>
                          <Tag>
                            {question.difficulty === "easy"
                              ? "简单"
                              : question.difficulty === "medium"
                                ? "中等"
                                : "困难"}
                          </Tag>
                        </Space>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </div>
        );

      default:
        return null;
    }
  };

  // 底部按钮
  const renderFooter = () => {
    return (
      <div style={{ textAlign: "right" }}>
        <Space>
          <Button onClick={onCancel}>取消</Button>
          {currentStep > 0 && (
            <Button onClick={() => setCurrentStep(currentStep - 1)}>
              上一步
            </Button>
          )}
          {currentStep === 0 && (
            <Button type="primary" onClick={() => form.submit()}>
              下一步
            </Button>
          )}
          {currentStep === 2 && (
            <Button
              type="primary"
              onClick={() => setCurrentStep(3)}
              disabled={selectedQuestions.length === 0}
            >
              预览试卷
            </Button>
          )}
          {currentStep === 3 && (
            <Button
              type="primary"
              onClick={handleFinish}
              loading={loading}
              icon={<CheckCircleOutlined />}
            >
              完成组卷
            </Button>
          )}
        </Space>
      </div>
    );
  };

  return (
    <Modal
      title="AI智能组卷"
      open={visible}
      onCancel={onCancel}
      footer={renderFooter()}
      width={1200}
      style={{ top: 20 }}
      destroyOnClose
    >
      <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />

      <div style={{ minHeight: 400 }}>
        <Form form={form} onFinish={handleAIGenerate}>
          {renderStepContent()}
        </Form>
      </div>
    </Modal>
  );
};

export default SmartComposer;
